package com.example.base.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.base.excetion.GlobalExcetion;
import com.example.base.system.domain.SysTable;
import com.example.base.system.domain.SysTableColumn;
import com.example.base.system.domain.vo.SysTableColumnVo;
import com.example.base.system.domain.vo.SysTableVo;
import com.example.base.system.mapper.DBMapper;
import com.example.base.system.mapper.SysTableMapper;
import com.example.base.system.service.SysTableColumnService;
import com.example.base.system.service.SysTableService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author X.I.O
 * @since 2024-02-21
 */
@Service
@Transactional
@CacheConfig(cacheNames = "SysTableServiceImpl")
public class SysTableServiceImpl extends ServiceImpl<SysTableMapper, SysTable> implements SysTableService {

    @Autowired
    private SysTableColumnService sysTableColumnService;


    @Override
    public SysTable getById(Serializable id){
        return super.getById(id);
    }

    @CacheEvict(cacheNames = "systable", key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @CacheEvict(cacheNames = "systable", key = "#systable.id")
    @Override
    public boolean updateById(SysTable systable) {
        return super.updateById(systable);
    }

    @CachePut(cacheNames = "systable", key = "#systable.id")
    public SysTable saveSysTable(SysTable systable) throws GlobalExcetion {
        super.save(systable);
        return systable;
    }

    @CacheEvict(cacheNames = "systable", key = "#systable.id")
    public SysTable updateSysTableById(SysTable systable) throws GlobalExcetion{
        super.updateById(systable);
        return systable;
    }


    public SysTable saveOrUpdateSysTable(SysTableVo systableVo) throws GlobalExcetion{
        SysTable systable=new SysTable();
        BeanUtils.copyProperties(systableVo,systable);
        if(systableVo.getId()!=null){
            SysTable systableEntity=super.baseMapper.selectById(systableVo.getId());
            if(systableEntity==null){
                throw new GlobalExcetion(1,"数据不存在");
            }
            if(!systableVo.getTableNo().equals(systableEntity.getTableNo())){
                SysTable sysTable=getSysTableByNo(systableEntity.getTableNo());
                if(sysTable!=null){
                    throw new GlobalExcetion(1,"table no标识已存在");
                }
            }
            systable.setUpdatetime(new Date());
            super.baseMapper.updateById(systable);
            dealSysTableColumnVos(systableVo.getColumns(),systableVo.getId(),systableVo.getTableTable());
        }else{
            SysTable sysTable=getSysTableByNo(systableVo.getTableNo());
            if(sysTable!=null){
                throw new GlobalExcetion(1,"table no标识已存在");
            }
            systable.setCreatetime(new Date());
            systable.setUpdatetime(new Date());
            super.baseMapper.insert(systable);
            dealSysTableColumnVos(systableVo.getColumns(),systable.getId(),systableVo.getTableTable());
        }
        return systable;
    }



    public void dealSysTableColumnVos(List<SysTableColumnVo> columnVos,Integer tableId,String tableName) throws GlobalExcetion {
        List<Map<String,Object>> mapList=getTableInfo(tableName);
        List<String> tableFieldList=mapList.stream().filter(e->e.containsKey("COLUMN_NAME")).map(e->(String)e.get("COLUMN_NAME")).collect(Collectors.toList());
        List<SysTableColumn> sysTableColumns=sysTableColumnService.getSysTableColumnByTableId(tableId);
        if(sysTableColumns!=null && sysTableColumns.size()>0){
            List<Integer> integers=columnVos.stream().filter(e->e.getId()!=null).map(SysTableColumnVo::getId).collect(Collectors.toList());
            if(integers.size() > 0){
                for (int i = 0; i < sysTableColumns.size() ; i++) {
                    SysTableColumn sysTableColumn=sysTableColumns.get(i);
                    if(!integers.contains(sysTableColumn.getId())){
                        sysTableColumnService.removeById(sysTableColumn.getId());
                    }
                }
            }
        }
        for (int i = 0; i < columnVos.size() ; i++) {
            SysTableColumnVo sysTableColumnVo=columnVos.get(i);
            sysTableColumnVo.setTableId(tableId);
            if(!tableFieldList.contains(sysTableColumnVo.getTableColumn())){
                throw new GlobalExcetion(1,tableName+"表没有此字段:"+sysTableColumnVo.getTableColumn()+"请先在数据库里面,添加此字段后在进行操作");
            }
            sysTableColumnService.saveOrUpdateSysTableColumn(sysTableColumnVo);
        }
    }

    public IPage<SysTable> page(Integer page, Integer pageSize) throws GlobalExcetion{
        LambdaQueryWrapper<SysTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(SysTable::getCreatetime);
        IPage<SysTable> iPage=super.baseMapper.selectPage(new Page(page,pageSize),lambdaQueryWrapper);
        return iPage;
    }

    @Autowired
    private DBMapper dbMapper;

    @Override
    public List<Map<String, String>> systemTableList() {
        String dataBaseName=dbMapper.selectDataBaseName();
        return dbMapper.selectAllTables(dataBaseName);
    }

    @Override
    public SysTable getSysTableByNo(String no) {
        LambdaQueryWrapper<SysTable> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysTable::getTableNo,no);
        return super.baseMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public List<Map<String, Object>> getTableInfo(String tableName) {
        String dataBaseName=dbMapper.selectDataBaseName();
        return dbMapper.selectTableInfo(dataBaseName,tableName);
    }

}
